package cn.fl.ref.fncprjpaysch.controller;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO ;
import cmm.mid.core.framework.page.Pager ;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.ref.fncprjpaysch.service.IFncPrjPaySchDJrnlService;
import cn.fl.ref.fncprjpaysch.service.IFncPrjPaySchMJrnlService;
import cn.fl.ref.fncprjpaysch.service.IFncPrjPaySchService;
import cn.fl.ref.fncprjpaysch.vo.FncPrjPaySchDJrnlVO;
import cn.fl.ref.fncprjpaysch.vo.FncPrjPaySchDVO;
import cn.fl.ref.fncprjpaysch.vo.FncPrjPaySchMJrnlVO;
import cn.fl.ref.fncprjpaysch.vo.FncPrjPaySchMVO;
import cn.fl.ref.fribaseinfo.service.IFriBaseInfoService;
import cn.fl.ref.fribaseinfo.transform.BankAccInfoVOTransform;
import cn.fl.ref.fribaseinfo.vo.BankAccInfoVO;
import cn.fl.ref.fribaseinfo.vo.FriBaseInfoVO;
import cn.fl.ref.scmbaseinfo.service.IScmBaseInfoService;
import cn.fl.ref.scmbaseinfo.vo.ScmBaseInfoVO;
import cn.fl.system.condition.SysBkAccInfoQueryCondition;
import cn.fl.system.constant.SysLogConstant;
import cn.fl.system.service.ISysBkAccInfoService;
import cn.fl.system.vo.SysBkAccInfoVO;
import fl.flow.facade.flow.constant.FlowConstant;
import fl.flow.facade.flow.dto.FlowStartParamsDTO;
import fl.flow.facade.flow.dto.FlowStartedDTO;
import fl.ref.contract.condition.FncPrjContMainQueryCondition ;
import fl.ref.fncprjbscinfo.constant.FncPrjBaseInfoConstant;
import fl.ref.fncprjpaysch.condition.FncPrjPaySchMCondition;
import fl.ref.fncprjpaysch.constant.FncPrjPaySchConstant;
import fl.ref.fncprjpaysch.constant.FncPrjPaySchConstant.FncPrjPaySchCanSt;
import fl.ref.fncprjpaysch.constant.FncPrjPaySchConstant.FncPrjPaySchMSt;
import fl.ref.fribaseinfo.condition.BankAccInfoQueryCondition;
import fl.ref.fribaseinfo.condition.FriBaseInfoQueryCondition;
import fl.ref.fribaseinfo.constant.FriBaseInfoConstant;
import fl.ref.fribaseinfo.dto.BankAccInfoDTO;
import fl.ref.fribaseinfo.service.IBankAccInfoApiService;
import fl.ref.scmbaseinfo.constant.ScmInfoConstant;

@Controller
@RequestMapping("/rfbase/fncprjpaysch")
public class FncPrjPaySchController {
	private static final Logger logger = LoggerFactory.getLogger(FncPrjPaySchController.class);

	@Autowired
	IFriBaseInfoService friBaseInfoService;
	
	@Autowired
	IFncPrjPaySchService fncPrjPaySchService;
	
	@Autowired
	IFncPrjPaySchMJrnlService fncPrjPaySchMJrnlService;
	
	@Autowired
	IFncPrjPaySchDJrnlService fncPrjPaySchDJrnlService;

	@Autowired
	private ISysBkAccInfoService sysBkAccInfoService;

	@Autowired
	private IBankAccInfoApiService bankAccInfoApiService;
	/**
	 * 本地数据字典服务
	 */
	@Autowired
	private ISysDictionaryApiService sysDictionaryApiService;
	@Autowired
	private IScmBaseInfoService scmBaseInfoService;
	/**
	 * 跳转到列表页面，初始化参数
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET })
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("rfbase/fncprjpaysch/fncPrjPaySchList");
		List<KeyValueVO> rePyTpCdLst = sysDictionaryApiService.getKvList(ScmInfoConstant.FNC_SCM_BSC_INFO_REPY_TP, 
				CurrentThreadContext.getFlServiceSysCd(), CurrentThreadContext.getCurrentOrgCd());//还款类别
		view.addObject("rePyTpCdLst", rePyTpCdLst);
		return view;
	}
	
	//还款发起
	@RequestMapping(value="toRepayPage.do", method = { RequestMethod.GET })
	public ModelAndView toRepayPage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("rfbase/fncprjpaysch/fncPrjPaySchApply");
		String pid = request.getParameter("pid");
		String payschid = request.getParameter("payschid");
		String repaystcd = request.getParameter("repaystcd");
		Map<String,Object> map = fncPrjPaySchService.selectRepayProjInfo(Long.parseLong(pid));
		Integer total0 = fncPrjPaySchService.selectExistArmt0Cnt(Long.parseLong(payschid));//记录是否指定项目所有还款都已结清		
		if(map.containsKey("PACCID") && map.get("PACCID")!=null){//付款账号，对应SysBk
			String paccid = map.get("PACCID")+"";
			SysBkAccInfoVO bkAccInfoVO = sysBkAccInfoService.selectById(Long.valueOf(paccid));
			if(bkAccInfoVO != null) {
				String paccno = bkAccInfoVO.getAccNo();
				view.addObject("paccno",paccno);
				view.addObject("bkAccInfoVO",bkAccInfoVO);
			}
			
		}

		if(map.containsKey("RACCID") && map.get("RACCID")!=null){//收款账号 对应recev BankAcc
			String raccid = map.get("RACCID")+"";
			BankAccInfoDTO bankAccInfoDTO = bankAccInfoApiService.selectById(Long.valueOf(raccid), CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
			if(bankAccInfoDTO !=null) {
				String raccno = bankAccInfoDTO.getAccNum();
				view.addObject("raccid",raccid);//机构收款账户ID
				view.addObject("raccno",raccno);//机构收款账户
			}
			
		}
		view.addObject("bscinfo", map);
		view.addObject("payschid", payschid);
		view.addObject("repaystcd", repaystcd);
		view.addObject("total0", total0);
		return view;
	}
	
	@RequestMapping(value="toRepayModifyPage.do", method = { RequestMethod.GET })
	public ModelAndView toRepayModifyPage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("rfbase/fncprjpaysch/fncPrjPaySchMod");
		String pid = request.getParameter("pid");
		String projid = request.getParameter("projid");
		//流程中页面，参数为主表流水id jrnlid
		String fid = request.getParameter("fid");
		String ffid = request.getParameter("ffid");
		String fsid = request.getParameter("fsid");
		String fsid2 = request.getParameter("fsid2");
		String fbid = request.getParameter("fbid");
		Map<String,Object> map = null;
		BaseLogUtils.info(logger, "toRepayModifyPage", "toRepayModifyPage*****************************************."
				, CurrentThreadContext.getCurrentUserName());
		
		if(projid != null){//公共查询页面根据项目号查看明细
			map = fncPrjPaySchService.selectRepayProjInfo(Long.parseLong(projid));
			BaseLogUtils.info(logger, "toRepayModifyPage", "toRepayModifyPage===========================."
					, CurrentThreadContext.getCurrentUserName());
			if(map != null) {
				String repayType = (String)map.get("REPAYTYPE");//还本方式
				if(StringUtils.isNoneBlank(repayType)) {
					Map<String, String> repayTypeMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(),FncPrjBaseInfoConstant.FNC_REPAY_TYPE);
					if(repayTypeMap != null && repayTypeMap.containsKey(repayType)){
						map.put("repayTypeNm", repayTypeMap.get(repayType));
					}
				}
				BigDecimal acXirr = (BigDecimal)map.get("ACXIRR");//实际XIRR
				if(acXirr != null) {
					map.put("ACXIRR",acXirr.multiply(new BigDecimal(100)).stripTrailingZeros().toPlainString());
				}
				
			}
			
			
			view = new ModelAndView("rfbase/fncprjpaysch/fncPrjPaySchDtl");
			//外部机构用
			view.addObject("pianflag",  request.getParameter("pianflag"));
			view.addObject("oper","pubview");
		}else if(fid != null){//流程查询页面根据还款主表编号查看明细
			FncPrjPaySchMJrnlVO tvo = fncPrjPaySchMJrnlService.selectById(Long.parseLong(fid));
			Long tid = tvo.getSchmId();
			map = fncPrjPaySchService.selectRepayProjInfoByMid(tid);
			view = new ModelAndView("rfbase/fncprjpaysch/fncPrjPaySchSynDtl");
			view.addObject("oper","priview");
			view.addObject("jrnlid",fid);
		}else if(fsid != null){//主动还款发起人确认页面根据还款主表编号同步实际到账并查看明细
			FncPrjPaySchMJrnlVO tvo = fncPrjPaySchMJrnlService.selectById(Long.parseLong(fsid));
			Long tid = tvo.getSchmId();
			map = fncPrjPaySchService.selectRepayProjInfoByMid(tid);
			view = new ModelAndView("rfbase/fncprjpaysch/fncPrjPaySchSynDtl");
			view.addObject("oper","synview");
			view.addObject("jrnlid",fsid);
		}else if(fsid2 != null){//主动还款发起人确认页面根据还款主表编号同步实际到账并查看明细
			FncPrjPaySchMJrnlVO tvo = fncPrjPaySchMJrnlService.selectById(Long.parseLong(fsid2));
			Long tid = tvo.getSchmId();
			map = fncPrjPaySchService.selectRepayProjInfoByMid(tid);
			view = new ModelAndView("rfbase/fncprjpaysch/fncPrjPaySchSynDtl");
			view.addObject("oper","synview2");
			view.addObject("jrnlid",fsid2);
		}else if(fbid != null){//被动还款确认资金到账页面根据还款主表编号修改还款基础信息
			FncPrjPaySchMJrnlVO tvo = fncPrjPaySchMJrnlService.selectById(Long.parseLong(fbid));
			Long tid = tvo.getSchmId();
			map = fncPrjPaySchService.selectRepayProjInfoByMid(tid);
			view = new ModelAndView("rfbase/fncprjpaysch/fncPrjPayBscMod");
			view.addObject("oper","modbsc");
			view.addObject("jrnlid",fbid);
		}else if(ffid != null){//被动还款发起人确认页面根据还款主表编号修改明细
			FncPrjPaySchMJrnlVO tvo = fncPrjPaySchMJrnlService.selectById(Long.parseLong(ffid));
			Long tid = tvo.getSchmId();
			map = fncPrjPaySchService.selectRepayProjInfoByMid(tid);
			view = new ModelAndView("rfbase/fncprjpaysch/fncPrjPaySchFncMod");
			view.addObject("oper","modnext");
			view.addObject("jrnlid",ffid);
		}else if(pid != null){//还款驳回后修改
			FncPrjPaySchMJrnlVO tvo = fncPrjPaySchMJrnlService.selectById(Long.parseLong(pid));
			Long tid = tvo.getSchmId();
			map = fncPrjPaySchService.selectRepayProjInfoByMid(tid);
			view = new ModelAndView("rfbase/fncprjpaysch/fncPrjPaySchMod");
			view.addObject("oper","mod");
			view.addObject("jrnlid",pid);
		}
		
		if(map.containsKey("PACCID") && map.get("PACCID")!=null){//付款账号 ，对应SysBk
			String paccid = map.get("PACCID")+"";
			SysBkAccInfoVO bkAccInfoVO = sysBkAccInfoService.selectById(Long.valueOf(paccid));
			if(bkAccInfoVO != null) {
				String paccno = bkAccInfoVO.getAccNo();
				view.addObject("paccno",paccno);
			}
			
		}

		if(map.containsKey("RACCID") && map.get("RACCID")!=null){//收款账号, 对应recev BankAcc
			String raccid = map.get("RACCID")+"";
			BankAccInfoDTO bankAccInfoDTO = bankAccInfoApiService.selectById(Long.valueOf(raccid), CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
			if(bankAccInfoDTO != null) {
				String raccno = bankAccInfoDTO.getAccNum();
				view.addObject("raccno",raccno);
			}
			
		}
		view.addObject("bscinfo", map);
		//add 融资报价方案信息 by gengchunlan 20190228
		if(null!=map.get("FNCSCMID") && !"".equals(map.get("FNCSCMID").toString())){
			ScmBaseInfoVO scmBaseInfo = scmBaseInfoService.selectById(Long.parseLong(map.get("FNCSCMID").toString()));
			view.addObject("scmBaseInfo",scmBaseInfo);
		}//end by gengchunlan 20190228
		BaseLogUtils.info(logger, "toRepayModifyPage", "toRepayModifyPage%%%%%%%%%%%%%%%%%%%%%%%%%%%"
				, CurrentThreadContext.getCurrentUserName());
		
		return view;
	}
	
	/**
	 * 加载机构列表选择框
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/initInstList.do" ,method = {RequestMethod.GET})
	public @ResponseBody  List<FriBaseInfoVO>  initInstList(HttpServletRequest request, HttpServletResponse response) {
		List<FriBaseInfoVO> lstVO = friBaseInfoService.searchList(new FriBaseInfoQueryCondition());
		return lstVO;
	}
	
	/**
	 * 加载金融机构收款户选择框
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/initRecvList.do" ,method = {RequestMethod.GET})
	public @ResponseBody  List<BankAccInfoVO>  initRecvList(HttpServletRequest request, HttpServletResponse response) {
		FriBaseInfoQueryCondition condition = new FriBaseInfoQueryCondition();
		String instid = request.getParameter("insId");
		if(instid != null && !instid.trim().equals("")){
			condition.setId(Long.parseLong(instid));
		}
		BankAccInfoQueryCondition bankAccInfoQC = new BankAccInfoQueryCondition();
		bankAccInfoQC.setFundRasInsId(Long.parseLong(instid));
		bankAccInfoQC.setSysCd(CurrentThreadContext.getCurrentSysCd());
		bankAccInfoQC.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
		List<BankAccInfoDTO> banklstdto = bankAccInfoApiService.searchList(bankAccInfoQC);
		List<BankAccInfoVO> voLst = BankAccInfoVOTransform.toVOList(banklstdto);
		return voLst;
	}
	
	/**
	 * 加载狮桥支付账户选择框
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/initPayList.do" ,method = {RequestMethod.GET})
	public @ResponseBody  List<SysBkAccInfoVO>  initPayList(HttpServletRequest request, HttpServletResponse response) {
		SysBkAccInfoQueryCondition qc = new SysBkAccInfoQueryCondition();
		qc.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
		List<SysBkAccInfoVO> bkAccList = sysBkAccInfoService.searchList(qc);
		return bkAccList;
	}
	
	/**
	 * 加载还款管理列表
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/initGrid.do" ,method = {RequestMethod.GET})
	public @ResponseBody Map<String, Object>  initGrid(HttpServletRequest request, HttpServletResponse response) {
		String idTmp = request.getParameter("fncInsId");
		String rePyTpCd = request.getParameter("rePyTpCd");
		String prjNm = request.getParameter("prjNm");
		FncPrjPaySchMCondition condition = new FncPrjPaySchMCondition();
		if(StringUtils.isNotEmpty(rePyTpCd)){
			condition.setRepyTp(Integer.parseInt(rePyTpCd));
		}
		if(StringUtils.isNotEmpty(idTmp)){
			condition.setFundRasInsId(Long.parseLong(idTmp));
		}
		if(StringUtils.isNotEmpty(prjNm)){
			condition.setPrjNm(prjNm);
		}
//		List<Map<String, Object>> prjPaySchLst = fncPrjPaySchService.selectRepayList(fundRasInsId);
		List<Map<String, Object>> prjPaySchLst = fncPrjPaySchService.selectRepayListByCnd(condition);
		Map<String, String> insTypCdMap = sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(),
				CurrentThreadContext.getCurrentOrgCd(),
				FriBaseInfoConstant.FUND_RAS_INS_BASE_INFO_INS_TYPE_CD);
		if(prjPaySchLst != null){
			for(Map<String, Object> m : prjPaySchLst){
				if(m.get("INSTYPECD")!=null){
					if (insTypCdMap.containsKey(m.get("INSTYPECD"))) {
						m.put("INSTYPENM", insTypCdMap.get(m.get("INSTYPECD")));
					}
				}
			}
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("Rows", prjPaySchLst);
		map.put("Total", prjPaySchLst.size());
		return map;
	}
	
	/**
	 * 加载还款融资端明细列表
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/initCost0Grid.do" ,method = {RequestMethod.GET})
	public @ResponseBody Map<String, Object>  initCost0Grid(HttpServletRequest request, HttpServletResponse response) {
		String idTmp = request.getParameter("payschid");
		Long payschid = -1L;
		if(idTmp != null && !idTmp.equals("")){
			payschid = Long.parseLong(idTmp);
		}
//		List<FncPrjPaySchDVO> payDLst = fncPrjPaySchService.selectCostDetlLst(payschid);
		List<Map<String,Object>> mapLst = fncPrjPaySchService.selectCost0DetlLst(payschid);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("Rows", mapLst);
		map.put("Total", mapLst.size());
		return map;
	}
	
	/**
	 * 加载还款明细列表
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/initDetlGrid.do" ,method = {RequestMethod.GET})
	public @ResponseBody Map<String, Object>  initDetlGrid(HttpServletRequest request, HttpServletResponse response) {
		String idTmp = request.getParameter("payschid");
		Long payschid = -1L;
		if(idTmp != null && !idTmp.equals("")){
			payschid = Long.parseLong(idTmp);
		}
		List<FncPrjPaySchDVO> payDLst = fncPrjPaySchService.selectRepayDetlLst(payschid);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("Rows", payDLst);
		map.put("Total", payDLst.size());
		return map;
	}
	
	/**
	 * 加载还款融资端明细列表
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/initCost0JrnlGrid.do" ,method = {RequestMethod.GET})
	public @ResponseBody Map<String, Object>  initCost0JrnlGrid(HttpServletRequest request, HttpServletResponse response) {
		String idTmp = request.getParameter("jrnlid");
		Long jrnlid = -1L;
		if(idTmp != null && !idTmp.equals("")){
			jrnlid = Long.parseLong(idTmp);
		}
		List<Map<String,Object>> mapLst = fncPrjPaySchDJrnlService.selectRepayCost0Lst(jrnlid);
		try{//遍历 payDLst
			ListIterator<Map<String,Object>>  iterator = mapLst.listIterator();
	        while (iterator.hasNext()) {
	        	Map<String,Object> cupayJrnl = iterator.next();
	        	//根据还款流水获取还款明细表
				if(null != cupayJrnl.get("ID") && !"".equals(cupayJrnl.get("ID"))){//还款流水明细表id
					Map<String, Object> map=fncPrjPaySchService.selectPayDetailByJrnl(Long.parseLong(cupayJrnl.get("ID").toString()));
					if(map!=null && map.get("payAccId")!=null && !"".equals(map.get("payAccId").toString()) ){
						cupayJrnl.put("payAccId",map.get("payAccId").toString());
					}
					if(map!=null && map.get("payAccNm")!=null && !"".equals(map.get("payAccNm").toString()) ){
						cupayJrnl.put("payAccNm",(map.get("payAccNm").toString()));
					}
					if(map!=null && map.get("payAccNoHtml")!=null && !"".equals(map.get("payAccNoHtml").toString()) ){
						cupayJrnl.put("payAccNoHtml",(map.get("payAccNoHtml").toString()));	
					}
					if(map!=null && map.get("rcvpymtAccId")!=null && !"".equals(map.get("rcvpymtAccId").toString()) ){
						cupayJrnl.put("rcvpymtAccId",(Long.parseLong(map.get("rcvpymtAccId").toString())));
					}
					if(map!=null && map.get("rcvpymtAccNoHtml")!=null && !"".equals(map.get("rcvpymtAccNoHtml").toString()) ){
						cupayJrnl.put("rcvpymtAccNoHtml",(map.get("rcvpymtAccNoHtml").toString()));
					}	
					iterator.remove();
			        iterator.add(cupayJrnl);
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("Rows", mapLst);
		map.put("Total", mapLst.size());
		BaseLogUtils.info(logger, "initCost0JrnlGrid", "initCost0JrnlGrid%%%%%%"
				, CurrentThreadContext.getCurrentUserName());
		return map;
	}
	
	/**
	 * 加载还款明细列表
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/initDetlJrnlGrid.do" ,method = {RequestMethod.GET})
	public @ResponseBody Map<String, Object>  initDetlJrnlGrid(HttpServletRequest request, HttpServletResponse response) {
		String idTmp = request.getParameter("jrnlid");
		Long jrnlid = -1L;
		if(idTmp != null && !idTmp.equals("")){
			jrnlid = Long.parseLong(idTmp);
		}
		List<FncPrjPaySchDJrnlVO> payDLst = fncPrjPaySchDJrnlService.selectJrnlRepayDetlLst(jrnlid);
		try{
			//遍历 payDLst
			ListIterator<FncPrjPaySchDJrnlVO>  iterator = payDLst.listIterator();
	        while (iterator.hasNext()) {
	        	FncPrjPaySchDJrnlVO cupayJrnl = iterator.next();
	        	//根据还款流水获取还款明细表
				if(null != cupayJrnl.getId() && !"".equals(cupayJrnl.getId())){//PAY_SCH_ID 还款主表id
					Map<String, Object> map=fncPrjPaySchService.selectPayDetailByJrnl(cupayJrnl.getId());
					if(map!=null && map.get("payAccId")!=null && !"".equals(map.get("payAccId").toString()) ){
						cupayJrnl.setPayAccId(Long.parseLong(map.get("payAccId").toString()));
					}
					if(map!=null && map.get("payAccNm")!=null && !"".equals(map.get("payAccNm").toString()) ){
						cupayJrnl.setPayAccNm(map.get("payAccNm").toString());
					}
					if(map!=null && map.get("payAccNoHtml")!=null && !"".equals(map.get("payAccNoHtml").toString()) ){
						cupayJrnl.setPayAccNoHtml(map.get("payAccNoHtml").toString());	
					}
					if(map!=null && map.get("rcvpymtAccId")!=null && !"".equals(map.get("rcvpymtAccId").toString()) ){
						cupayJrnl.setRcvpymtAccId(Long.parseLong(map.get("rcvpymtAccId").toString()));
					}
					if(map!=null && map.get("rcvpymtAccNoHtml")!=null && !"".equals(map.get("rcvpymtAccNoHtml").toString()) ){
						cupayJrnl.setRcvpymtAccNoHtml(map.get("rcvpymtAccNoHtml").toString());
					}	
					iterator.remove();
			        iterator.add(cupayJrnl);
				}
	       }
		}catch(Exception e){
			e.printStackTrace();
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("Rows", payDLst);
		map.put("Total", payDLst.size());
		return map;
	}

	/**
	 * 启动流程
	 */
	@RequestMapping(value = "/addFlowStart.do", method = { RequestMethod.POST})
	@ResponseBody
	public Object addFlowStart(HttpServletRequest request, HttpServletResponse response) {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		String id = request.getParameter("id");
		String procDefKey = request.getParameter("procDefKey");
		String procDefId = request.getParameter("procDefId");
		String procNo = request.getParameter("procNo");
		String jsondata = request.getParameter("jsondata");
		String flowId = "";
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "addFlowStart", SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY, CurrentThreadContext.getCurrentUserName());
			return result;
		}
		FncPrjPaySchMVO mvo = fncPrjPaySchService.selectById(Long.parseLong(id));
		if(mvo.getRepayStcd() != null && mvo.getRepayStcd().equals(FncPrjPaySchMSt.CHECKING.getKey())){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("还款处理中!不能再次发起还款!");
			BaseLogUtils.info(logger, "addFlowStart", SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY, CurrentThreadContext.getCurrentUserName());
			return result;
		}
		JSONObject post_json = new JSONObject(); 
		if(jsondata != null){
			post_json = JSONObject.parseObject(jsondata);
			String paySchId = post_json.getString("payschid");
			JSONArray grid0 = post_json.getJSONArray("griddata0");
			JSONArray grid1 = post_json.getJSONArray("griddata1");
			JSONArray data = post_json.getJSONArray("formdata");
			List<FncPrjPaySchDVO> dvoLst = new ArrayList<FncPrjPaySchDVO>();
			try {
				for(int i=0;i<grid1.size();i++){
					JSONObject djson = grid1.getJSONObject(i);
					if(paySchId!=null && djson.get("arAmt")!=null && Double.parseDouble(djson.get("arAmt")+"")!=0){
						FncPrjPaySchDVO dvo = new FncPrjPaySchDVO();
						dvo.setId(Long.parseLong(djson.get("id")+""));
						dvo.setActualAmt(new BigDecimal(djson.get("actualAmt")+""));
						dvo.setFloatAmt(new BigDecimal(djson.get("floatAmt")+""));
						BigDecimal paidUpAmt = new BigDecimal(djson.get("paidUpAmt")+"");
						BigDecimal feeAmt = new BigDecimal(djson.get("feeAmt")+"");
						double value = feeAmt.add(dvo.getFloatAmt()).subtract(paidUpAmt).subtract(dvo.getActualAmt()).doubleValue();
						if(value == 0){
							dvo.setCanSt(FncPrjPaySchCanSt.ALLCHECKING.getKey());
						}else{
							dvo.setCanSt(FncPrjPaySchCanSt.PARTCHECKING.getKey());
						}
						if(djson.containsKey("feeRem") && StringUtils.isNotBlank(djson.getString("feeRem"))){
							dvo.setFeeRem(djson.getString("feeRem"));
						}
						dvoLst.add(dvo);
					}
				}
				for(int i=0;i<grid0.size();i++){
					JSONObject djson = grid0.getJSONObject(i);
					if(paySchId!=null && djson.get("AR_AMT")!=null && Double.parseDouble(djson.get("AR_AMT")+"")!=0){
						FncPrjPaySchDVO dvo = new FncPrjPaySchDVO();
						dvo.setId(Long.parseLong(djson.get("ID")+""));
						dvo.setActualAmt(new BigDecimal(djson.get("ACTUAL_AMT")+""));
						dvo.setFloatAmt(new BigDecimal(djson.get("FLOAT_AMT")+""));
						if(djson.containsKey("FEE_REM") && StringUtils.isNotBlank(djson.getString("FEE_REM"))){
							dvo.setFeeRem(djson.getString("FEE_REM"));
						}
						BigDecimal paidUpAmt = new BigDecimal(djson.get("PAID_UP_AMT")+"");
						BigDecimal feeAmt = new BigDecimal(djson.get("FEE_AMT")+"");
						double value = feeAmt.add(dvo.getFloatAmt()).subtract(paidUpAmt).subtract(dvo.getActualAmt()).doubleValue();
						if(value == 0){
							dvo.setCanSt(FncPrjPaySchCanSt.ALLCHECKING.getKey());
						}else{
							dvo.setCanSt(FncPrjPaySchCanSt.PARTCHECKING.getKey());
						}
						dvoLst.add(dvo);
					}
				}
				if(dvoLst.size()>0){
					fncPrjPaySchService.batchUpdateRepayDetl(dvoLst);
				}
				FncPrjPaySchMVO vo = new FncPrjPaySchMVO();
				for(int i=0;i<data.size();i++){
					JSONObject objTmp = data.getJSONObject(i);
					String key = objTmp.getString("name");
					String value = objTmp.getString("value");
					if(key.equals("payschid")){
						vo.setId(Long.parseLong(value == null ? "-1" : value));
						vo.setRepayStcd(2);//还款主表置为处理中
						continue;
					}
					if(key.equals("recvAcc_val") && value != null && !value.trim().equals("")){
						vo.setRcvpymtAccId(Long.parseLong(value));
						continue;
					}
					if(key.equals("payAcc") && value != null && !value.trim().equals("")){
						vo.setPayAccId(Long.parseLong(value));
						continue;
					}
				}
				if(vo.getId()!=null && dvoLst.size()>0){
					fncPrjPaySchService.upateRepayMain(vo);
				}
				Long mjrnlid = fncPrjPaySchMJrnlService.selectNewSchMJrnlId();//通过主表流水id发起流程
				FncPrjPaySchDJrnlVO djvo = new FncPrjPaySchDJrnlVO();
				djvo.setJrnlMId(mjrnlid);
				djvo.setPaySchId(vo.getId());
				fncPrjPaySchService.insertIntoSchDJrnlFromAgo(djvo);
				FncPrjPaySchMJrnlVO mjvo = new FncPrjPaySchMJrnlVO();
				mjvo.setJrnlId(mjrnlid);
				mjvo.setSchmId(vo.getId());
				flowId = mjrnlid+"";
				fncPrjPaySchService.insertIntoSchMJrnlFromAgo(mjvo);
			} catch (Exception e) {
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(e.getMessage());
				BaseLogUtils.error(logger, "addFlowStart", "异常"+post_json.toString(), e);
				e.printStackTrace();
				return result;
			}
			result = startFlow(flowId,result, procDefKey, procDefId, procNo);
		}
		
		
		return result;
	}
	
	public DataResultVO startFlow(String flowId,DataResultVO result,String procDefKey, String procDefId, String procNo){
		FlowStartParamsDTO flowStartParamsDTO = new FlowStartParamsDTO();
		try {
			//流程定义Key和流程定义ID 如果是前端选择的则直接指定,如果不是则系统自动按照配置选择唯一一条记录,如果找不到会提示
			flowStartParamsDTO.setAudStsCd(FlowConstant.FLOW_CHECK_STATE_IN);
			flowStartParamsDTO.setWordsInTheTable(FncPrjPaySchConstant.SCH_FLOW_RPAYS);
			flowStartParamsDTO.setProcDefKey(procDefKey);
			flowStartParamsDTO.setProcDefId(procDefId);
			flowStartParamsDTO.setProcNo(procNo);
			flowStartParamsDTO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
			flowStartParamsDTO.setBusinessKey(flowId);
			flowStartParamsDTO.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
			flowStartParamsDTO.setBuOrgCd(CurrentThreadContext.getCurrentBuOrgCd());
			flowStartParamsDTO.setSysCd(CurrentThreadContext.getCurrentSysCd());
			flowStartParamsDTO.setInitiator(String.valueOf(CurrentThreadContext.getCurrentUserId()));
			flowStartParamsDTO.setInitiatorNm(CurrentThreadContext.getCurrentUserName());
			flowStartParamsDTO.setProcPriority(FlowConstant.FLOW_PRIORITY_EMERGENCY);//优先级,可以在界面定义
			flowStartParamsDTO.setBusinessType(FncPrjPaySchConstant.FLOW_BUSINESS_TYP_FNC_PRJ_PAY_SCH_M);//确认用不用
			flowStartParamsDTO.setModelTyp("R006");//需要和流程配置中的模块类型匹配
			flowStartParamsDTO.setSearchDesc(CurrentThreadContext.getCurrentOrgDispNm()+"、还款流程大字段参数未定!");
			DataResultDTO dataResultDTO = fncPrjPaySchService.addFlowStart(flowStartParamsDTO);
			if(!dataResultDTO.getCode().equals(BaseExceptionConstant.BASE_EXCEPTION_CODE_200)){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_OPERATE_FAIL);
			}
			if(null!=dataResultDTO && null!=dataResultDTO.getData()){
				FlowStartedDTO flowStartedDTO = (FlowStartedDTO) dataResultDTO.getData();
				if(StringUtils.isNotBlank(flowStartedDTO.getNextOperUsrNames())){
	                result.setInfo("下一个节点操作人:"+flowStartedDTO.getNextOperUsrNames());
	            }else{
	                result.setInfo("流程发起成功");
	            }
				result.setSuccess(BaseConstant.IS_YESNO_YES);
			}
			//录入资金付款信息--陈君
//			this.fncCapPayeeInfoService.addCappaysch(Long.parseLong(schid));
		} catch (Exception e) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "addFlowStart", "错误[Exception],请求参数：" + JSONObject.parseObject(flowStartParamsDTO.toString()) + " -ERROR:" +e.getMessage(), CurrentThreadContext.getCurrentUserName());
			e.printStackTrace();
			return result;
		}
		
		return result;
	}
	
	//融资经理修改
	@RequestMapping(value="/updateData.do" ,method = {RequestMethod.POST})
	public @ResponseBody Object updateData(@RequestBody Object formdata) throws ParseException{
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject post_json = new JSONObject(); 
		if(formdata != null){
			post_json = JSONObject.parseObject(formdata.toString());
			String jrnlid = post_json.getString("jrnlid");
			JSONArray grid0 = post_json.getJSONArray("griddata0");
			JSONArray grid1 = post_json.getJSONArray("griddata1");
			JSONArray data = post_json.getJSONArray("formdata");
			List<FncPrjPaySchDJrnlVO> dvoLst = new ArrayList<FncPrjPaySchDJrnlVO>();
			List<FncPrjPaySchDVO> ddvoLst = new ArrayList<FncPrjPaySchDVO>();
			try {
				for(int i=0;i<grid1.size();i++){
					JSONObject djson = grid1.getJSONObject(i);
					if(jrnlid!=null && djson.get("arAmt")!=null && Double.parseDouble(djson.get("arAmt")+"")!=0){
						FncPrjPaySchDJrnlVO dvo = new FncPrjPaySchDJrnlVO();
						FncPrjPaySchDVO ddvo = new FncPrjPaySchDVO();
						
						dvo.setId(Long.parseLong(djson.get("id")+""));
						dvo.setActualAmt(new BigDecimal(djson.get("actualAmt")+""));
						dvo.setFloatAmt(new BigDecimal(djson.get("floatAmt")+""));

						ddvo.setId(Long.parseLong(djson.get("schDId")+""));
						ddvo.setActualAmt(new BigDecimal(djson.get("actualAmt")+""));
						ddvo.setFloatAmt(new BigDecimal(djson.get("floatAmt")+""));
						
						BigDecimal paidUpAmt = new BigDecimal(djson.get("paidUpAmt")+"");
						BigDecimal feeAmt = new BigDecimal(djson.get("feeAmt")+"");
						double value = feeAmt.add(dvo.getFloatAmt()).subtract(paidUpAmt).subtract(dvo.getActualAmt()).doubleValue();
						if(value == 0){
							ddvo.setCanSt(FncPrjPaySchCanSt.ALLCHECKING.getKey());
							dvo.setCanSt(FncPrjPaySchCanSt.ALLCHECKING.getKey());
						}else{
							ddvo.setCanSt(FncPrjPaySchCanSt.PARTCHECKING.getKey());
							dvo.setCanSt(FncPrjPaySchCanSt.PARTCHECKING.getKey());
						}
						if(StringUtils.isNotBlank(djson.getString("feeRem"))){
							dvo.setFeeRem(djson.getString("feeRem"));
							ddvo.setFeeRem(djson.getString("feeRem"));
						}
						dvoLst.add(dvo);
						
						ddvoLst.add(ddvo);
					}
				}
				for(int i=0;i<grid0.size();i++){
					JSONObject djson = grid0.getJSONObject(i);
					if(jrnlid!=null && djson.get("AR_AMT")!=null && Double.parseDouble(djson.get("AR_AMT")+"")!=0){
						FncPrjPaySchDJrnlVO dvo = new FncPrjPaySchDJrnlVO();
						FncPrjPaySchDVO ddvo = new FncPrjPaySchDVO();
						
						dvo.setId(Long.parseLong(djson.get("ID")+""));
						dvo.setActualAmt(new BigDecimal(djson.get("ACTUAL_AMT")+""));
						dvo.setFloatAmt(new BigDecimal(djson.get("FLOAT_AMT")+""));
						
						ddvo.setId(Long.parseLong(djson.get("SCH_DID")+""));
						ddvo.setActualAmt(new BigDecimal(djson.get("ACTUAL_AMT")+""));
						ddvo.setFloatAmt(new BigDecimal(djson.get("FLOAT_AMT")+""));
						
						BigDecimal paidUpAmt = new BigDecimal(djson.get("PAID_UP_AMT")+"");
						BigDecimal feeAmt = new BigDecimal(djson.get("FEE_AMT")+"");
						double value = feeAmt.add(dvo.getFloatAmt()).subtract(paidUpAmt).subtract(dvo.getActualAmt()).doubleValue();
						if(value == 0){
							ddvo.setCanSt(FncPrjPaySchCanSt.ALLCHECKING.getKey());
							dvo.setCanSt(FncPrjPaySchCanSt.ALLCHECKING.getKey());
						}else{
							ddvo.setCanSt(FncPrjPaySchCanSt.PARTCHECKING.getKey());
							dvo.setCanSt(FncPrjPaySchCanSt.PARTCHECKING.getKey());
						}
						if(StringUtils.isNotBlank(djson.getString("FEE_REM"))){
							dvo.setFeeRem(djson.getString("FEE_REM"));
							ddvo.setFeeRem(djson.getString("FEE_REM"));
						}
						dvoLst.add(dvo);

						ddvoLst.add(ddvo);
					}
				}
				if(dvoLst.size()>0 && ddvoLst.size()>0){
					fncPrjPaySchService.batchUpdateRepayDetl(ddvoLst);
					fncPrjPaySchDJrnlService.batchUpdateJrnlRepayDetl(dvoLst);
				}
				FncPrjPaySchMVO vo = new FncPrjPaySchMVO();
				FncPrjPaySchMJrnlVO fncPrjPaySchMJrnlVO = new FncPrjPaySchMJrnlVO();//流水主表VO
				for(int i=0;i<data.size();i++){
					JSONObject objTmp = data.getJSONObject(i);
					String key = objTmp.getString("name");
					String value = objTmp.getString("value");
					if(key.equals("payschid")){
						vo.setId(Long.parseLong(value == null ? "-1" : value));
						vo.setRepayStcd(2);//还款主表置为处理中
						continue;
					}
					if(key.equals("recvAcc_val") && value != null && !value.trim().equals("")){
						vo.setRcvpymtAccId(Long.parseLong(value));
						fncPrjPaySchMJrnlVO.setRcvpymtAccId(Long.parseLong(value));
						continue;
					}
					if(key.equals("payAcc") && value != null && !value.trim().equals("")){
						vo.setPayAccId(Long.parseLong(value));
						continue;
					}
					if(key.equals("jrnlid") && value != null && !value.trim().equals("")){
						fncPrjPaySchMJrnlVO.setJrnlId(Long.parseLong(value));
						continue;
					}
				}
				
				if(vo.getId()!=null && dvoLst.size()>0){
					fncPrjPaySchService.upateRepayMain(vo);//更新还款主表
				}
				if(fncPrjPaySchMJrnlVO.getJrnlId()!=null && fncPrjPaySchMJrnlVO.getRcvpymtAccId() != null){
					fncPrjPaySchMJrnlService.modify(fncPrjPaySchMJrnlVO);//更新还款流水主表的收款帐号信息
				}
				
			} catch (Exception e) {
				map.put("msgcode", "0001");
				map.put("errormsg", e.getMessage());
				BaseLogUtils.error(logger, "updateData", "异常"+post_json.toString(), e);
				e.printStackTrace();
				return map;
			}		
		}
		map.put("msgcode", "0000");
		return map;
	}
	
	//被动还款发起人确认，可修改本金
	@RequestMapping(value="/updateBData.do" ,method = {RequestMethod.POST})
	public @ResponseBody Object updateBData(@RequestBody Object formdata) throws ParseException{
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject post_json = new JSONObject(); 
		if(formdata != null){
			post_json = JSONObject.parseObject(formdata.toString());
			String jrnlid = post_json.getString("jrnlid");
			JSONArray grid0 = post_json.getJSONArray("griddata0");
			JSONArray grid1 = post_json.getJSONArray("griddata1");
			JSONArray data = post_json.getJSONArray("formdata");
			List<FncPrjPaySchDJrnlVO> dvoLst = new ArrayList<FncPrjPaySchDJrnlVO>();
			List<FncPrjPaySchDVO> ddvoLst = new ArrayList<FncPrjPaySchDVO>();
			try {
				for(int i=0;i<grid1.size();i++){
					JSONObject djson = grid1.getJSONObject(i);
					if(jrnlid!=null && djson.get("arAmt")!=null && Double.parseDouble(djson.get("arAmt")+"")!=0){
						FncPrjPaySchDJrnlVO dvo = new FncPrjPaySchDJrnlVO();
						FncPrjPaySchDVO ddvo = new FncPrjPaySchDVO();
						
						dvo.setId(Long.parseLong(djson.get("id")+""));
						dvo.setActualAmt(new BigDecimal(djson.get("actualAmt")+""));
						dvo.setFloatAmt(new BigDecimal(djson.get("floatAmt")+""));

						ddvo.setId(Long.parseLong(djson.get("schDId")+""));
						ddvo.setActualAmt(new BigDecimal(djson.get("actualAmt")+""));
						ddvo.setFloatAmt(new BigDecimal(djson.get("floatAmt")+""));
						BigDecimal paidUpAmt = new BigDecimal(djson.get("paidUpAmt")+"");
						BigDecimal feeAmt = new BigDecimal(djson.get("feeAmt")+"");
						double value = feeAmt.add(dvo.getFloatAmt()).subtract(paidUpAmt).subtract(dvo.getActualAmt()).doubleValue();
						if(value == 0){
							dvo.setCanSt(FncPrjPaySchCanSt.ALLCHECKING.getKey());
							ddvo.setCanSt(FncPrjPaySchCanSt.ALLCHECKING.getKey());
						}else{
							dvo.setCanSt(FncPrjPaySchCanSt.PARTCHECKING.getKey());
							ddvo.setCanSt(FncPrjPaySchCanSt.PARTCHECKING.getKey());
						}
						dvo.setFeeAmt(new BigDecimal(djson.get("feeAmt")+""));
						ddvo.setFeeAmt(new BigDecimal(djson.get("feeAmt")+""));
						if(StringUtils.isNotBlank(djson.getString("feeRem"))){
							dvo.setFeeRem(djson.getString("feeRem"));
							ddvo.setFeeRem(djson.getString("feeRem"));
						}
						if(djson.get("actPymtDt") != null && StringUtils.isNotBlank(djson.get("actPymtDt")+"")){
							String actPymtDt = djson.get("actPymtDt")+"";
							String subsActPymtDt = actPymtDt.substring(0, 10);
							Date date = DateUtils.parseDate(subsActPymtDt, "yyyy-MM-dd");
							dvo.setActPymtDt(date);
							ddvo.setActPymtDt(date);
						}
						if(djson.get("actPymtAmt") != null && StringUtils.isNotBlank(djson.get("actPymtAmt")+"")){
							String actPymtAmt = djson.get("actPymtAmt")+"";
							dvo.setActPymtAmt(new BigDecimal(actPymtAmt));
							ddvo.setActPymtAmt(new BigDecimal(actPymtAmt));
						}
						dvoLst.add(dvo);
						ddvoLst.add(ddvo);
					}
				}
				for(int i=0;i<grid0.size();i++){
					JSONObject djson = grid0.getJSONObject(i);
					if(jrnlid!=null && djson.get("AR_AMT")!=null && Double.parseDouble(djson.get("AR_AMT")+"")!=0){
						FncPrjPaySchDJrnlVO dvo = new FncPrjPaySchDJrnlVO();
						FncPrjPaySchDVO ddvo = new FncPrjPaySchDVO();
						dvo.setId(Long.parseLong(djson.get("ID")+""));
						dvo.setActualAmt(new BigDecimal(djson.get("ACTUAL_AMT")+""));
						dvo.setFloatAmt(new BigDecimal(djson.get("FLOAT_AMT")+""));

						ddvo.setId(Long.parseLong(djson.get("SCH_DID")+""));
						ddvo.setActualAmt(new BigDecimal(djson.get("ACTUAL_AMT")+""));
						ddvo.setFloatAmt(new BigDecimal(djson.get("FLOAT_AMT")+""));
						BigDecimal paidUpAmt = new BigDecimal(djson.get("PAID_UP_AMT")+"");
						BigDecimal feeAmt = new BigDecimal(djson.get("FEE_AMT")+"");
						double value = feeAmt.add(dvo.getFloatAmt()).subtract(paidUpAmt).subtract(dvo.getActualAmt()).doubleValue();
						if(value == 0){
							dvo.setCanSt(FncPrjPaySchCanSt.ALLCHECKING.getKey());
							ddvo.setCanSt(FncPrjPaySchCanSt.ALLCHECKING.getKey());
						}else{
							dvo.setCanSt(FncPrjPaySchCanSt.PARTCHECKING.getKey());
							ddvo.setCanSt(FncPrjPaySchCanSt.PARTCHECKING.getKey());
						}
						if(StringUtils.isNotBlank(djson.getString("FEE_REM"))){
							dvo.setFeeRem(djson.getString("FEE_REM"));
							ddvo.setFeeRem(djson.getString("FEE_REM"));
						}
						//保存实际付款时间
						if(StringUtils.isNotBlank(djson.getString("ACT_PYMT_DT"))){
							dvo.setActPymtDt(DateUtils.parseDate(djson.getString("ACT_PYMT_DT"), "yyyy-MM-dd"));
							ddvo.setActPymtDt(DateUtils.parseDate(djson.getString("ACT_PYMT_DT"), "yyyy-MM-dd"));
						}
						//保存实际还款金额
						if(djson.getBigDecimal("ACT_PYMT_AMT") != null){
							dvo.setActPymtAmt(djson.getBigDecimal("ACT_PYMT_AMT"));
							ddvo.setActPymtAmt(djson.getBigDecimal("ACT_PYMT_AMT"));
						}
						
						dvoLst.add(dvo);
						ddvoLst.add(ddvo);
					}
				}
				if(dvoLst.size()>0){
					fncPrjPaySchService.batchUpdateRepayDetl(ddvoLst);
					fncPrjPaySchDJrnlService.batchUpdateJrnlRepayDetl(dvoLst);
				}
				FncPrjPaySchMVO vo = new FncPrjPaySchMVO();
				for(int i=0;i<data.size();i++){
					JSONObject objTmp = data.getJSONObject(i);
					String key = objTmp.getString("name");
					String value = objTmp.getString("value");
					if(key.equals("payschid")){
						vo.setId(Long.parseLong(value == null ? "-1" : value));
						vo.setRepayStcd(2);//还款主表置为处理中
						continue;
					}
					if(key.equals("recvAcc_val") && value != null && !value.trim().equals("")){
						vo.setRcvpymtAccId(Long.parseLong(value));
						continue;
					}
					if(key.equals("payAcc_val") && value != null && !value.trim().equals("")){
						vo.setPayAccId(Long.parseLong(value));
						continue;
					}
				}
				if(vo.getId()!=null && dvoLst.size()>0){
					fncPrjPaySchService.upateRepayMain(vo);
				}
			} catch (Exception e) {
				map.put("msgcode", "0001");
				map.put("errormsg", e.getMessage());
				BaseLogUtils.error(logger, "updateData", "异常"+post_json.toString(), e);
				e.printStackTrace();
				return map;
			}		
		}
		map.put("msgcode", "0000");
		return map;
	}
	
	//流程中修改
	@RequestMapping(value="/updateFData.do" ,method = {RequestMethod.POST})
	public @ResponseBody Object updateFData(@RequestBody Object formdata) throws ParseException{
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject post_json = new JSONObject(); 
		if(formdata != null){
			post_json = JSONObject.parseObject(formdata.toString());
			JSONArray data = post_json.getJSONArray("formdata");
			try {
				FncPrjPaySchMVO vo = new FncPrjPaySchMVO();
				for(int i=0;i<data.size();i++){
					JSONObject objTmp = data.getJSONObject(i);
					String key = objTmp.getString("name");
					String value = objTmp.getString("value");
					if(key.equals("payschid")){
						vo.setId(Long.parseLong(value == null ? "-1" : value));
						vo.setRepayStcd(2);//还款主表置为处理中
						continue;
					}
					if(key.equals("recvAcc_val") && value != null && !value.trim().equals("")){
						vo.setRcvpymtAccId(Long.parseLong(value));
						continue;
					}
					if(key.equals("payAcc_val") && value != null && !value.trim().equals("")){
						vo.setPayAccId(Long.parseLong(value));
						continue;
					}
				}
				if(vo.getId()!=null){
					fncPrjPaySchService.upateRepayMain(vo);
				}
			} catch (Exception e) {
				map.put("msgcode", "0001");
				map.put("errormsg", e.getMessage());
				BaseLogUtils.error(logger, "updateFData", "异常"+post_json.toString(), e);
				e.printStackTrace();
				return map;
			}		
		}
		map.put("msgcode", "0000");
		return map;
	}
	
	@RequestMapping(value="/synFundSys.do" ,method = {RequestMethod.POST})
	public @ResponseBody Object synFundSys(@RequestBody Object formdata) throws BaseException{
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject post_json = JSONObject.parseObject(formdata.toString());
		if(post_json.containsKey("jrnlid") && post_json.get("jrnlid")!=null){
			Long pid = Long.parseLong(post_json.get("jrnlid")+"");
			map = fncPrjPaySchService.synFundSys(pid);
			return map;
		}
		map.put("msgcode", "0000");
		return map;
	}
	
	/**
	 * 还款计划表页面;
	 * @param request
	 * @return
	 */
	@RequestMapping("/repaymentPlanPage.do")
	public String repaymentPlanPage(HttpServletRequest request) {
		return "rfbase/fncprjpaysch/repaymentPlanPage" ;
	}
	
	
	/**
	 * 还款计划表查询 
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/repaymentPlanPageList.do")
	@ResponseBody
	public Object repaymentPlanPageList(FncPrjContMainQueryCondition qc,HttpServletRequest request) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize") ;
		
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}
		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize)) ;
		}

	
		page.setCondition(qc);

		page = this.fncPrjPaySchService.repaymentPlanPageList(page);
		List<Map<String, Object>> list = (List<Map<String, Object>>) page.getResultList();
		BaseLogUtils.info(logger, "repaymentPlanPageList", "查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		return new ListPageVO<Map<String, Object>>(list, page.getTotalCount());
	}
	
	/**
	 *  费用项  
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/feeList.do")
	@ResponseBody
	public List<KeyValueVO> feeList(HttpServletRequest request, HttpServletResponse response) {
		List<KeyValueVO> feeList = sysDictionaryApiService.getKvList(FncPrjPaySchConstant.FNC_PRJ_PAY_SCH_FEE_CLS_CD, 
				CurrentThreadContext.getFlServiceSysCd(), CurrentThreadContext.getCurrentOrgCd());
		return feeList ;
	}
	
	
	/**
	 * 实际付款流水页面
	 * @param request
	 * @return
	 */
	@RequestMapping("/realPayPage.do")
	public String realPayPage(HttpServletRequest request) {
		return "rfbase/fncprjpaysch/realPayPage";
	}
	
	
	/**
	 * 实际付款流水查询
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/realPayPageList.do")
	@ResponseBody
	public Object realPayPageList(FncPrjContMainQueryCondition qc,HttpServletRequest request) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}
		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

	
		page.setCondition(qc);

		page = this.fncPrjPaySchService.realPayPageList(page);
		List<Map<String, Object>> list = (List<Map<String, Object>>) page.getResultList();
		BaseLogUtils.info(logger, "repaymentPlanPageList", "查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		return new ListPageVO<Map<String, Object>>(list, page.getTotalCount());
	}
	
	
	/**
	 * 实际付款流水查询导出
	 */
	@RequestMapping(value = "/realPayExport.do")
	@ResponseBody
	public Object realPayExport(FncPrjContMainQueryCondition qc,HttpServletRequest request) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_BK_EXPORT_SUCC);
		try {
			
			String path = this.fncPrjPaySchService.realPayExport(qc,request.getParameter("from"));
			if(StringUtils.isNotEmpty(path)){
				result.setSuccess(BaseConstant.IS_YESNO_YES);
				result.setInfo(SysLogConstant.LOG_BK_EXPORT_SUCC);
				result.setData(path);
				BaseLogUtils.info(logger, "exportAssInfo", "实际付款流水查询导出成功", CurrentThreadContext.getCurrentUserName());
			}
		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.error(logger, "exportAssInfo", "实际付款流水查询导出失败.", CurrentThreadContext.getCurrentUserName(), ex);
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "exportAssInfo", "实际付款流水查询导出,系统错误..", CurrentThreadContext.getCurrentUserName(), ex);
		}
		
		return result;
	}
	/**
	 * 跳转到付款项确认页面
	 * @param request
	 * @param response
	 * @return
	 * 2018年7月17日 
	 * lxb
	 */
	@RequestMapping(value="tocheckRepay.do", method = { RequestMethod.GET })
	public ModelAndView tocheckRepay(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("rfbase/fncprjpaysch/fncPrjPaySchCheck");
		String id = request.getParameter("id");
		BaseLogUtils.info(logger, "tocheckRepay", "跳转到付款项确认页面.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		Map<String,Object> map = null;
		//流程查询页面根据还款主表编号查看明细
		if (StringUtils.isNotBlank(id)) {
		
			FncPrjPaySchMJrnlVO tvo = fncPrjPaySchMJrnlService.selectById(Long.parseLong(id));
			Long tid = tvo.getSchmId();
			map = fncPrjPaySchService.selectRepayProjInfoByMid(tid);
			view.addObject("jrnlid",id);
		}
		if(map.containsKey("PACCID") && map.get("PACCID")!=null){//付款账号 ，对应SysBk
			String paccid = map.get("PACCID")+"";
			SysBkAccInfoVO bkAccInfoVO = sysBkAccInfoService.selectById(Long.valueOf(paccid));
			if(bkAccInfoVO != null) {
				String paccno = bkAccInfoVO.getAccNo();
				view.addObject("paccno",paccno);
			}
			
		}

		if(map.containsKey("RACCID") && map.get("RACCID")!=null){//收款账号, 对应recev BankAcc
			String raccid = map.get("RACCID")+"";
			BankAccInfoDTO bankAccInfoDTO = bankAccInfoApiService.selectById(Long.valueOf(raccid), CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
			if(bankAccInfoDTO != null) {
				String raccno = bankAccInfoDTO.getAccNum();
				view.addObject("raccno",raccno);
			}
			
		}
		view.addObject("bscinfo", map);
		List<Map<String,Object>> payDLst = fncPrjPaySchDJrnlService.selectJrnlRepayAllLst(Long.parseLong(id));
		if (payDLst!=null) {
			for (int i = 0; i < payDLst.size(); i++) {
				Map<String,Object> obj= payDLst.get(i);
				if (Double.valueOf(obj.get("ACTUAL_AMT").toString())!=0) {
					//备注
					if (obj.get("FEE_REM")==null) {
						obj.put("FEE_REM",(String)map.get("FUNDRASINSNM")+(String)obj.get("COST_NM"));
					}
				}else {
					payDLst.remove(i);
					i--;
				}
				
			}
		}
		view.addObject("payDLst", payDLst);
		return view;
	}
	/**
	 * 付款项确认保存
	 */
	@RequestMapping(value = "/savecheckRepay.do")
	@ResponseBody
	public Object savecheckRepay(FncPrjContMainQueryCondition qc,HttpServletRequest request) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_BK_EXPORT_SUCC);
		try {
				String jsondata = request.getParameter("jsondata");
				JSONObject map= JSONObject.parseObject(jsondata);
				for (String key:map.keySet() ) {
					FncPrjPaySchDJrnlVO vo=new FncPrjPaySchDJrnlVO();
					vo.setId(Long.valueOf(key));
					vo.setFeeRem(map.getString(key));
					fncPrjPaySchDJrnlService.modify(vo);
				}
				result.setSuccess(BaseConstant.IS_YESNO_YES);
				result.setInfo(SysLogConstant.LOG_BK_EXPORT_SUCC);
				
				BaseLogUtils.info(logger, "savecheckRepay", "付款项确认保存成功", CurrentThreadContext.getCurrentUserName());
			
		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.error(logger, "savecheckRepay", "付款项确认保存失败.", CurrentThreadContext.getCurrentUserName(), ex);
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "savecheckRepay", "付款项确认保存,系统错误..", CurrentThreadContext.getCurrentUserName(), ex);
		}
		
		return result;
	}
}
